package org.lbspoc.springboot1.boot.service;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.lbspoc.springboot1.boot.SpringUtils;
import org.lbspoc.springboot1.boot.model.LbsInfo;
import org.springframework.core.env.Environment;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;

public class MongoUtil {
	private static MongoUtil _instance = new MongoUtil();
	private MongoClient client = null;
	private MongoDatabase db;
	private String collectName;

	private MongoUtil() {
		// TODO Auto-generated constructor stub
		Environment ev = SpringUtils.getApplicationContext().getEnvironment();
		String host = ev.getProperty("mongodb.ip");
		int port = Integer.parseInt(ev.getProperty("mongodb.port"));
		ServerAddress sa = new ServerAddress(host, port);
		
		String user = ev.getProperty("mongodb.user");
		String adminDb = ev.getProperty("mongodb.userDB");
		String passwd = ev.getProperty("mongodb.passwd");
		MongoCredential mc = MongoCredential.createCredential(user, 
				adminDb, passwd.toCharArray());
		List<MongoCredential> mcList = new ArrayList<MongoCredential>();
		mcList.add(mc);
		client = new MongoClient(sa, mcList);
		
		String dbName = ev.getProperty("mongodb.db");
		db = client.getDatabase(dbName);
		collectName = ev.getProperty("mongodb.collection");
	}

	public static MongoUtil getInstance() {
		return _instance;
	}
	
	public MongoDatabase getDB() {
		return db;
	}
	
	public String getCollectionName() {
		return collectName;
	}
	
	public void close() {
		client.close();
	}
	
	public void fillDocument(Document doc, LbsInfo info) {
		doc.put("user_id", info.getUser_id());
		doc.put("latitude", info.getLatitude());
		doc.put("longitude", info.getLongitude());
		doc.put("last_updated_ts", info.getLast_updated_ts());
	}
	
	public LbsInfo docToLbsInfo(Document doc) {
		LbsInfo info = new LbsInfo();
		info.setUser_id(doc.getLong("user_id"));
		info.setLatitude(doc.getDouble("latitude"));
		info.setLongitude(doc.getDouble("longitude"));
		
		info.setLast_updated_ts(doc.getString("last_updated_ts"));
		return info;
	}
}
